var express = require("express");
var router = express.Router();
const { Room, RoomGroup } = require("../models");
const { Op } = require("sequelize");
/**
 * 查询所有宿舍
 */
router.get("/", async (req, resp, next) => {
  const where = {};
  // 取查询参数
  const groupId = req.query.groupId;
  const roomName = req.query.roomName;
  // 取json req.body
  if (groupId) {
    where.groupId = groupId;
  }
  if (roomName) {
    where.roomName = {
      [Op.like]: `%${roomName}%`,
    };
  }

  const result = await Room.findAll({
    where,
    include: [
      {
        model: RoomGroup,
        as: "rg",
      },
    ],
  });
  resp.send(result);
});

/**
 * 创建宿舍
 */
router.post("/", async (req, resp, next) => {
  const { roomName, groupId } = req.body;
  const result = await Room.create({
    roomName,
    groupId,
  });
  resp.send(result);
});

/**
 * 删除宿舍
 */
router.delete("/:id", async (req, resp, next) => {
  const id = req.params.id; // 取路径参数
  const result = await Room.destroy({
    where: {
      id,
    },
  });
  resp.send(result);
});

module.exports = router;
